import React, { lazy, Suspense } from 'react';
import { ActivityIndicator } from 'antd-mobile';
import { ILazyLoadProps } from '@/interface';

const LazyLoad: React.FC<ILazyLoadProps> = props => {
  const _renderLazy = () => {
    const { component, delay, ...other } = props;
    let cop = component;
    if (!component || component.constructor.name !== 'Promise') {
      cop = import('./lazyLoadError');
    }

    const Lazy = lazy(() => {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve(cop);
        }, delay || 300);
      });
    });

    return <Lazy {...other} />;
  };

  return (
    <Suspense fallback={<ActivityIndicator text="Loading..." />}>
      {_renderLazy()}
    </Suspense>
  );
};

export default LazyLoad;
